package com.zy.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.time.Duration;
import java.util.Collections;
import java.util.UUID;

/**
 * [redis分布式锁的简单实现]
 *
 * @author : [itnan]
 * @version : [v1.0]
 * @createTime : [2024/12/17 17:00]
 */

public class SimpleRedisLock implements ILock {

    private String key;
    private StringRedisTemplate stringRedisTemplate;
    private static final String ID_PREFIX = UUID.randomUUID().toString() + "-";

    private static final String KEY_PREFIX = "lock:";

    public SimpleRedisLock(String key, StringRedisTemplate stringRedisTemplate) {
        this.key = key;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //提前把lua脚本准备好
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec 锁持有的时间,到期释放
     * @return true: 获取锁成功 false: 获取锁失败
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = Thread.currentThread().getId() + "";
        String value = ID_PREFIX + threadId;
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + key, value, Duration.ofSeconds(timeoutSec));
        //包装类到基本类,自动拆箱有可能出现空指针
        //return BooleanUtil.isTrue(isLock); 做自动拆箱一定要看空指针的风险
        return Boolean.TRUE.equals(isLock);
    }

    /**
     * lua脚本版释放锁
     */
    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + key), ID_PREFIX + Thread.currentThread().getId());

    }

    /**
     * 释放锁
     */
    /*@Override
    public void unlock() {
        String threadId = Thread.currentThread().getId() + "";
        String value = ID_PREFIX + threadId;
        String currentValue = stringRedisTemplate.opsForValue().get(KEY_PREFIX + key);
        //判断是否是当前线程的锁
        if (value.equals(currentValue)){
            //是的话删除
            stringRedisTemplate.delete(KEY_PREFIX + key);
        }
        //不是当前线程的锁,不删除,并回滚之前的事务

    }*/
}
